import {
	baseUrl
} from './config.js'

export const apiResquest = (prams, loading = true) => {
	console.log(prams, ';pramsprams');
	//prams是调用的接口API的参数

	//请求头设置
	let headerData = {
		'content-type': 'application/json',
		'token': uni.getStorageSync('token'),
		'openid': uni.getStorageSync('openid'),
	}


	return new Promise((resolve, reject) => {
		let url = baseUrl + prams.url; //请求的网络地址和局地的api地址组合
		if (loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}
		console.log('loading:' + loading)
		return uni.request({
			url: url,
			data: {
				...prams.query,
				openid: prams.query.openid || uni.getStorageSync('openid')
			},
			method: prams.method,
			header: headerData,
			success: (res) => {
				if (loading) {
					uni.hideLoading()
				}
				const {
					statusCode,
					data
				} = res

				if (statusCode == 200) {
					if (data.code == 1) {
						resolve(data);
					} else if (res.code == 401) {
						uni.showToast({
							title: data.msg,
							icon: "error"
						});
						var pages = getCurrentPages() // 获取栈实例
						let currentPage = pages[pages.length - 1]['$page'][
							'fullPath'
						] //当前页面路径(带参数)
						console.log(currentPage);
						uni.setStorageSync('redirect_url', currentPage);
						setTimeout(function() {
							uni.navigateTo({
								url: "/pages/wechatLogin/wechatLogin"
							})
						}, 1000)
					} else {
						if (data.msg === '请去登录') {
							var pages = getCurrentPages() // 获取栈实例
							let currentPage = pages[pages.length - 1]['$page'][
								'fullPath'
							] //当前页面路径(带参数)
							console.log(currentPage);
							uni.setStorageSync('redirect_url', currentPage);
							setTimeout(function() {
								uni.navigateTo({
									url: "/pages/wechatLogin/wechatLogin"
								})
							}, 1000)
							setTimeout(function() {
								uni.navigateTo({
									url: "/pages/wechatLogin/wechatLogin"
								})
							}, 1000)
							
						}
						uni.showToast({
							title: data.msg,
							icon: "error"
						})
					}
				} else {
					uni.showToast({
						title: data.msg,
						icon: "error"
					})
				}

			},
			fail: (err) => {
				reject(err);
				console.log(err)
				if (loading) {
					uni.hideLoading()
				}
			},
			complete: () => {
				console.log('请求完成')
				if (loading) {
					uni.hideLoading()
				}
			}
		});
	})
}